// import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import ListofDetails from './components/ListofDetail';
import { useRequest } from '@umijs/hooks';
import { queryoversaleTable, downloadExcel, queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

// let hiddenData = null;
const TableList = (props) => {
  const { location: {state} } = props;
  const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  const columns = [
    {
      title: '超售事故单号',
      // hideInSearch: true,
      dataIndex: 'overId',
      width: 100,
    },{
      title: '超售类型',
      key: 'type',
      dataIndex: 'type',
      initialValue: '',
      width: 100,
      filters: [
        {text: '改签', value: '0'},
        {text: '退票', value: '1'},
      ],
      valueEnum: {
        '': '全部',
        '0': '改签',
        '1': '退票',
      },
    },
    {
      title: '补偿单号',
      hideInSearch: true,
      dataIndex: 'orderId',
      width: 100,
    },
    {
      title: '补偿单状态',
      key: 'status',
      hideInSearch: true,
      dataIndex: 'status',
      initialValue: '',
      width: 120,
      filters: [
        {text: '草稿', value: '0'},
        {text: '审核中',value: '1'},
        {text: '通过', value: '2'},
        {text: '生效', value: '3'},
        {text: '关闭', value: '4'},
        {text: '未通过', value: '5'},
        {text: '驳回', value: '6'},
        {text: '逾期', value: '8'}
      ],
      valueEnum: {
        '': '全部',
        '0': '草稿',
        '1': '审核中',
        '2': '通过',
        '3': '生效',
        '4': '关闭',
        '5': '未通过',
        '6':'驳回',
        '8':'逾期'
      },
    },
    {
      title: '领取状态',
      key: 'receiveStatus',
      initialValue: '',
      dataIndex: 'receiveStatus',
      width: 120,
      filters: [
        {text: '未领取', value: '0'},
        {text: '已领取', value: '1'},
        {text: '领取中', value: '2'},
      ],
      valueEnum: {
        '': '全部',
        '0': '未领取',
        '1': '已领取',
        '2': '领取中',
      },
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      key: 'flightNo',
      width: 100,
      required: true,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return (
          <Input
            {...rest}
            onChange={e => {
              e.target.value = formatFlightNo(e.target.value);
              rest.onChange(e.target.value)
            }}
            maxLength={6}
            placeholder="3U"
          />
        );
      },
    },
   {
    title: '航班日期',
    dataIndex: 'flightDate',
    width: 100,
    hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 7,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order:6,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '计划起飞',
      hideInSearch: true,
      dataIndex: 'oldPlanDate',
      width: 100,
    },
    {
      title: '旅客搜索',
      dataIndex: 'keySearch',
      hideInTable: true,
      width: 100,
    },
    {
      // 多个查询选项
      title: '服务航站',
      dataIndex: 'serviceCity',
      width: 100,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    // {
    //   title: '支付方式',
    //   key: 'payType',
    //   initialValue: '',
    //   hideInTable: true,
    //   dataIndex: 'payType',
    //   width: 100,
    //   filters: [
    //     {text: '微信', value: '0'},
    //     {text: '银联',value: '1'},
    //     {text: '现金', value: '2'},
    //     {text: '支付宝', value: '3'}
    //   ],
    //   valueEnum: {
    //     '': '全部',
    //     '0': '微信',
    //     '1': '银联',
    //     '2': '现金',
    //     '3': '支付宝',
    //   },
    // },
    
    {
      title: '旅客姓名',
      hideInSearch: true,
      dataIndex: 'paxName',
      width: 100,
    },
    {
      title: '客票号',
      hideInSearch: true,
      dataIndex: 'tktNo',
      width: 100,
    },
    {
      title: '航段',
      hideInSearch: true,
      dataIndex: 'segment',
      width: 100,
    },
    {
      title: '总金额',
      hideInSearch: true,
      dataIndex: 'sumMoney',
      width: 100,
    },
    {
      title: '补偿金额',
      hideInSearch: true,
      dataIndex: 'payMoney',
      width: 100,
    },
    {
      title: '改签航班',
      hideInSearch: true,
      dataIndex: 'overBookFlightNo',
      width: 100,
    },
    {
      title: '改签日期',
      hideInSearch: true,
      dataIndex: 'overBookFlightDate',
      width: 100,
    },
    {
      title: '改签时间',
      hideInSearch: true,
      dataIndex: 'planDate',
      width: 100,
    },
    {
      title: '申请人',
      hideInSearch: true,
      dataIndex: 'createUser',
      width: 100,
    },
    {
      title: '审核人',
      hideInSearch: true,
      dataIndex: 'auditor',
      width: 100,
    },
    {
      title: '发放人',
      hideInSearch: true,
      dataIndex: 'grantUser ',
      width: 100,
    },
  ];
  const [overId, setoverId] = useState('0');

  const [dataScope, setDataScope] = useState('0');
  const onScopeChange = useCallback(e => {
    setDataScope(e.target.value);
  }, []);

  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  useEffect(() => {
    if (actionRef.current && inited) {
       reloadTable();
    } else {
      setInited(true);
    }
  }, [dataScope, inited]);

    // 切换清空搜索
  //   useEffect(() => {
  //     hiddenData = null
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  //   }, [])

    // 从消息页跳转过来及审核单，初始化加载查询参数
    useEffect(()=>{
      if (ref.current && state && sessionStorage.getItem('firstLoad')){
        setDataScope('0')
        ref.current.setFieldsValue({
          startDate: state.flightDate ? moment(state.flightDate) : '',
          endDate: state.flightDate ? moment(state.flightDate) : '',
          flightNo: state.flightNo ? state.flightNo : '',
          keySearch: state.accidentId ? state.accidentId : '',
        })
        reloadTable();
        sessionStorage.removeItem('firstLoad')
      }
    }, [ref.current])


  // 点击到详情的方法，顺便传值 id 过去
  const toDdetails = useCallback(e => {
    handleModalVisible(true);
  }, []);
  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {

    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params, queryType: dataScope }
    } else {
      if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment()
        })
        // hiddenData = {}
      }
      // return { ...hiddenData, ...params, queryType: dataScope }
      return { ...params, queryType: dataScope }
    }
  }, [dataScope]);

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  //导出方法
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadExcel(searchParams)
    // let res = downloadExcel()
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '旅客超售列表'+time+'.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <div id="oversaleIndexId" style={{position:"relative"}}>
      <ProTable
        headerTitle={
          <>
            <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>超售列表</span>
            <Radio.Group buttonStyle="solid" defaultValue={dataScope} value={dataScope} onChange={onScopeChange}>
              <Radio.Button value="0">全部</Radio.Button>
              <Radio.Button value="1">我发起的</Radio.Button>
              <Radio.Button value="2">草稿</Radio.Button>
            </Radio.Group>
          </>
        }
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 1100, y: height }}
        size='small'
        className={`${styles.oversaleTable} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val)
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNo: hiddenData.flightNo,
            //     type: hiddenData.type,
            //     receiveStatus:hiddenData.receiveStatus,
            //     overId: hiddenData.overId,
            //     keySearch: hiddenData.keySearch,
            //     serviceCity: hiddenData.serviceCity
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          }
        }}
        toolBarRender={() => [
        <AuthComponent authCode="overSale.index.export">
           <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]}>
            导出
          </Button>
        </AuthComponent>
        ]}
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          dataScope?params['queryType'] = dataScope:'0';
          if (!params['startDate'] && !params['endState']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment()
            })
          }
          if (!params['receiveStatus']) {
            ref.current.setFieldsValue({
              receiveStatus: ''
            })
          }
          if (!params['type']) {
            ref.current.setFieldsValue({
              type: ''
            })
          }
          handleSearchParams(params);
          return queryoversaleTable(params);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        onRow={record => {
          return {
            onClick: () => {
              if(AuthComponent.getAuth('overSale.index.detail')){
                setoverId(record.overId);
                toDdetails();
              }
            },
          };
        }}
        columns={columns}
        rowSelection={rowSelection}
        rowKey="overId"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
      {createModalVisible && (
        <ListofDetails
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
          overId={overId}
        />
      )}
    </div>
  );
};

export default Form.create()(TableList);
